<template>
  <div class="policy-search-container">
    <header class="header-bar">
      <h1>政策溯源</h1>
      <div class="header-actions">
        <button class="btn-refresh" @click="refreshData">
          <span class="icon">🔄</span>
          <span class="text">刷新数据</span>
        </button>
      </div>
    </header>

    <div class="search-content">
      <!-- 搜索框区域 -->
      <div class="search-box-wrapper">
        <div class="search-box">
          <input
            v-model="searchKeyword"
            type="text"
            :placeholder="searchPlaceholder"
            @keyup.enter="performSearch"
          />
          <button @click="performSearch" :disabled="isLoading">
            <span v-if="!isLoading">搜索</span>
            <span v-else class="loading-dots">搜索中</span>
          </button>
        </div>
        <div class="search-tips">
          热门搜索：
          <span 
            v-for="(tag, index) in hotKeywords" 
            :key="index"
            class="search-tag"
            @click="searchByTag(tag)"
          >
            {{ tag }}
          </span>
        </div>
      </div>

      <!-- 搜索结果区域 -->
      <div class="search-results">
        <transition name="fade" mode="out-in">
          <!-- 加载状态 -->
          <div v-if="isLoading" class="loading-state">
            <div class="spinner"></div>
            <p>正在搜索相关政策...</p>
          </div>
          
          <!-- 有搜索结果 -->
          <div v-else-if="searchResults.length > 0" class="results-container">
            <div class="results-header">
              <h2>找到 {{ searchResults.length }} 个相关政策组</h2>
              <div class="sort-options">
                <span>排序：</span>
                <select v-model="sortOption" @change="sortResults">
                  <option value="relevance">相关度</option>
                  <option value="date">最新日期</option>
                  <option value="count">政策数量</option>
                </select>
              </div>
            </div>
            
            <div class="results-grid">
              <div 
                v-for="group in searchResults" 
                :key="group.id" 
                class="policy-card"
                @click="goToPolicyTrace(group.id)"
              >
                <div class="card-header">
                  <h3>{{ group.title }}</h3>
                  <span class="relevance-badge">
                    {{ (group.relevance * 100).toFixed(0) }}% 相关
                  </span>
                </div>
                <div class="card-meta">
                  <span class="meta-item">
                    <span class="icon">📅</span>
                    <span class="text">最新：{{ formatDate(getLatestDate(group)) }}</span>
                  </span>
                  <span class="meta-item">
                    <span class="icon">📋</span>
                    <span class="text">{{ group.policies.length }} 条政策</span>
                  </span>
                </div>
                <p class="card-description">{{ group.description }}</p>
                <div class="policy-tags">
                  <span 
                    v-for="(level, index) in getUniqueLevels(group)" 
                    :key="index"
                    :class="['level-tag', 'level-' + level]"
                  >
                    {{ level }}
                  </span>
                </div>
                <div class="card-footer">
                  <span class="policy-examples">
                    {{ getPolicyExamples(group) }}
                  </span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 无搜索结果 -->
          <div v-else-if="searchPerformed" class="empty-state">
            <div class="empty-icon">🔍</div>
            <h3>没有找到与"{{ searchKeyword }}"相关的政策组</h3>
            <p>尝试使用不同的关键词或浏览我们的<a @click.prevent="showAllPolicies">全部政策</a></p>
          </div>
          
          <!-- 初始状态 -->
          <div v-else class="welcome-state">
            <div class="welcome-illustration">
              <div class="illustration-circle"></div>
              <div class="illustration-doc"></div>
              <div class="illustration-search"></div>
            </div>
            <h2>欢迎使用政策搜索</h2>
            <p>输入关键词查找相关政策组，或浏览<a @click.prevent="showAllPolicies">全部政策</a></p>
            <div class="quick-actions">
              <button @click="showAllPolicies">浏览全部政策</button>
              <button @click="showRecentPolicies">查看最近更新</button>
            </div>
          </div>
        </transition>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 数据状态
const searchKeyword = ref('')
const searchResults = ref([])
const isLoading = ref(false)
const searchPerformed = ref(false)
const sortOption = ref('relevance')
const hotKeywords = ref(['科技创新', '中小企业', '绿色能源', '税收优惠', '人才引进'])

// 生成更丰富的示例数据
function generateSampleData() {
  const sampleGroups = [
    {
      id: 1,
      title: "科技创新支持政策",
      description: "国家及地方关于科技创新的系列支持政策，涵盖研发补贴、税收优惠、人才引进等多方面内容，助力企业技术创新和产业升级。",
      policies: [
        { id: 101, title: "国家科技创新2030规划纲要", date: "2022-03-15", level: "国家", relevance: 0.95, 
          description: "国家层面科技创新长期规划，提出到2030年的发展目标和重点任务，包括重大科技项目布局和创新体系建设。" },
        { id: 102, title: "XX省科技创新十条政策措施", date: "2022-07-20", level: "省级", relevance: 0.85, 
          description: "省级科技创新支持政策，包括研发费用加计扣除、高新技术企业认定、科技成果转化奖励等具体措施。" },
        { id: 103, title: "XX市高新技术企业认定与补贴办法", date: "2023-01-10", level: "市级", relevance: 0.75, 
          description: "对首次认定的高新技术企业给予50万元奖励，对重新认定的给予20万元奖励，并配套税收优惠政策。" }
      ]
    },
    {
      id: 2,
      title: "中小企业扶持政策包",
      description: "各级政府对中小企业的全方位扶持措施，包括融资支持、税收减免、用工补贴等方面，助力中小企业健康发展。",
      policies: [
        { id: 201, title: "中华人民共和国中小企业促进法(2021修订)", date: "2021-09-01", level: "国家", relevance: 0.92, 
          description: "国家中小企业基本法律，保障中小企业公平参与市场竞争，规定财税支持、融资促进、创业扶持等政策措施。" },
        { id: 202, title: "XX省中小企业纾困与发展三年行动计划", date: "2022-05-12", level: "省级", relevance: 0.88, 
          description: "针对疫情后中小企业经营困难的专项帮扶措施，包括贷款贴息、租金减免、社保缓缴等一揽子政策。" },
        { id: 203, title: "XX市小微企业贷款贴息实施细则", date: "2022-11-05", level: "市级", relevance: 0.8, 
          description: "对符合条件的小微企业提供50%贷款利息补贴，单户企业年度贴息额度不超过20万元。" }
      ]
    },
    {
      id: 3,
      title: "绿色能源发展政策合集",
      description: "推动新能源和可再生能源发展的系列政策措施，包括光伏、风电等清洁能源的补贴和支持政策。",
      policies: [
        { id: 301, title: "十四五现代能源体系规划", date: "2021-12-30", level: "国家", relevance: 0.9, 
          description: "国家能源发展五年规划，明确新能源发展目标，到2025年非化石能源消费比重提高到20%左右。" },
        { id: 302, title: "XX省分布式光伏发电项目补贴政策", date: "2022-08-15", level: "省级", relevance: 0.82, 
          description: "对分布式光伏发电项目给予0.2元/度补贴，连续补贴5年，单个项目年度补贴不超过50万元。" }
      ]
    },
    {
      id: 4,
      title: "人才引进与培养政策",
      description: "各地吸引和培养高层次人才的政策措施，包括住房补贴、科研经费、子女教育等配套支持。",
      policies: [
        { id: 401, title: "XX市高层次人才引进实施办法", date: "2023-02-18", level: "市级", relevance: 0.87, 
          description: "对引进的A类人才给予200万元安家补贴，B类人才100万元，并提供科研启动经费和子女入学便利。" }
      ]
    }
  ]
  
  localStorage.setItem('policyGroupsData', JSON.stringify(sampleGroups))
  return sampleGroups
}

// 获取唯一政策级别
function getUniqueLevels(group) {
  const levels = new Set()
  group.policies.forEach(p => levels.add(p.level))
  return Array.from(levels)
}

// 获取最新政策日期
function getLatestDate(group) {
  return group.policies.reduce((latest, policy) => 
    policy.date > latest ? policy.date : latest, 
    group.policies[0].date
  )
}

// 格式化日期显示
function formatDate(dateStr) {
  const date = new Date(dateStr)
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
}

// 获取政策示例
function getPolicyExamples(group) {
  return group.policies.slice(0, 2).map(p => p.title).join("，")
}

// 排序结果
function sortResults() {
  switch(sortOption.value) {
    case 'date':
      searchResults.value.sort((a, b) => getLatestDate(b).localeCompare(getLatestDate(a)))
      break
    case 'count':
      searchResults.value.sort((a, b) => b.policies.length - a.policies.length)
      break
    default: // relevance
      searchResults.value.sort((a, b) => b.relevance - a.relevance)
  }
}

// 搜索功能
function performSearch() {
  if (!searchKeyword.value.trim()) {
    showAllPolicies()
    return
  }
  
  isLoading.value = true
  searchPerformed.value = true
  
  // 模拟API调用延迟
  setTimeout(() => {
    const allGroups = JSON.parse(localStorage.getItem('policyGroupsData')) || []
    
    searchResults.value = allGroups.filter(group => 
      group.title.includes(searchKeyword.value) || 
      group.description.includes(searchKeyword.value) ||
      group.policies.some(p => 
        p.title.includes(searchKeyword.value) || 
        p.description.includes(searchKeyword.value)
      )
    ).map(group => ({
      ...group,
      relevance: calculateRelevance(group, searchKeyword.value)
    }))
    
    sortResults()
    isLoading.value = false
  }, 800)
}

// 计算相关度
function calculateRelevance(group, keyword) {
  let score = 0
  
  // 标题匹配权重最高
  if (group.title.includes(keyword)) score += 0.5
  if (group.description.includes(keyword)) score += 0.3
  
  // 政策内容匹配
  const policyMatches = group.policies.filter(p => 
    p.title.includes(keyword) || p.description.includes(keyword)
  ).length
  
  score += (policyMatches / group.policies.length) * 0.2
  
  // 确保在0.7-1之间
  return Math.min(Math.max(score + 0.7, 0.7), 1)
}

// 通过标签搜索
function searchByTag(tag) {
  searchKeyword.value = tag
  performSearch()
}

// 显示所有政策
function showAllPolicies() {
  searchKeyword.value = ''
  searchPerformed.value = true
  const allGroups = JSON.parse(localStorage.getItem('policyGroupsData') || [])
  searchResults.value = allGroups.map(g => ({...g, relevance: 0.8}))
  sortResults()
}

// 显示最近政策
function showRecentPolicies() {
  searchKeyword.value = ''
  searchPerformed.value = true
  const allGroups = JSON.parse(localStorage.getItem('policyGroupsData')) || []
  searchResults.value = allGroups.map(g => ({...g, relevance: 0.8}))
  sortOption.value = 'date'
  sortResults()
}

// 刷新数据
function refreshData() {
  generateSampleData()
  if (searchKeyword.value) {
    performSearch()
  } else {
    showAllPolicies()
  }
}

function goToPolicyTrace(groupId) {
  router.push({ 
    name: 'PolicyTrace', 
    query: { groupId } 
  })
}

// 初始化数据
onMounted(() => {
  if (!localStorage.getItem('policyGroupsData')) {
    generateSampleData()
  }
  showAllPolicies()
})
</script>

<style scoped>
.policy-search-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--gradient-primary);
  color: var(--color-textPrimary);
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  transition: all 0.3s ease;
}

/* 头部样式 */
.header-bar {
  flex-shrink: 0;
  background: var(--color-navBg);
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 10px var(--color-shadow);
  color: var(--color-textPrimary);
  transition: all 0.3s ease;
}

.header-bar h1 {
  margin: 0;
  font-weight: 600;
  font-size: 1.8rem;
  color: var(--color-textPrimary);
}

.header-actions {
  display: flex;
  gap: 12px;
}

.btn-refresh {
  display: flex;
  align-items: center;
  gap: 6px;
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  color: var(--color-textPrimary);
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-refresh:hover {
  background: var(--color-tertiary);
  border-color: var(--color-borderHover);
}

.search-content {
  flex: 1;
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
  box-sizing: border-box;
}

/* 搜索框区域 */
.search-box-wrapper {
  margin-bottom: 30px;
  max-width: 800px;
  margin: 0 auto 30px;
  transition: all 0.3s ease;
}

.search-box {
  display: flex;
  margin-bottom: 10px;
  box-shadow: 0 4px 12px var(--color-shadow);
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.search-box input {
  flex: 1;
  padding: 14px 20px;
  font-size: 1.1rem;
  border: none;
  outline: none;
  background: var(--color-surface);
  color: var(--color-textPrimary);
  transition: all 0.3s ease;
}

.search-box input::placeholder {
  color: var(--color-textTertiary);
}

.search-box button {
  padding: 0 30px;
  background: var(--color-accent);
  color: white;
  border: none;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.search-box button:hover:not(:disabled) {
  background: var(--color-accentHover);
}

.search-box button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.loading-dots:after {
  content: '...';
  animation: dots 1.5s steps(5, end) infinite;
}

@keyframes dots {
  0%, 20% { content: '.'; }
  40% { content: '..'; }
  60%, 100% { content: '...'; }
}

.search-tips {
  font-size: 0.9rem;
  color: var(--color-textSecondary);
  text-align: center;
  transition: color 0.3s ease;
}

.search-tag {
  margin: 0 5px;
  color: var(--color-accent);
  cursor: pointer;
  text-decoration: underline;
  transition: color 0.3s ease;
}

.search-tag:hover {
  color: var(--color-accentHover);
}

/* 搜索结果区域 */
.search-results {
  min-height: 300px;
  transition: all 0.3s ease;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid var(--color-border);
  border-left-color: var(--color-accent);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.results-container {
  animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--color-divider);
  transition: all 0.3s ease;
}

.results-header h2 {
  margin: 0;
  font-size: 1.3rem;
  color: var(--color-textPrimary);
}

.sort-options {
  display: flex;
  align-items: center;
  gap: 10px;
  color: var(--color-textSecondary);
}

.sort-options select {
  padding: 6px 12px;
  border-radius: 4px;
  border: 1px solid var(--color-border);
  background: var(--color-surface);
  color: var(--color-textPrimary);
  transition: all 0.3s ease;
}

.results-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 25px;
}

/* 政策卡片样式 */
.policy-card {
  background: var(--color-surface);
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 12px var(--color-shadow);
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  height: 100%;
  border: 1px solid var(--color-border);
}

.policy-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px var(--color-shadow);
  border-color: var(--color-borderHover);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.card-header h3 {
  margin: 0;
  font-size: 1.2rem;
  color: var(--color-accent);
  flex: 1;
}

.relevance-badge {
  background: var(--color-tertiary);
  color: var(--color-accent);
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: 600;
}

.card-meta {
  display: flex;
  gap: 15px;
  font-size: 0.9rem;
  color: var(--color-textSecondary);
  margin-bottom: 12px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.card-description {
  color: var(--color-textPrimary);
  line-height: 1.6;
  margin-bottom: 15px;
  flex: 1;
}

.policy-tags {
  display: flex;
  gap: 8px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.level-tag {
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: 500;
}

.level-国家 {
  background: rgba(239, 68, 68, 0.1);
  color: var(--color-error);
}

.level-省级 {
  background: rgba(34, 197, 94, 0.1);
  color: var(--color-success);
}

.level-市级 {
  background: rgba(59, 130, 246, 0.1);
  color: var(--color-info);
}

.card-footer {
  font-size: 0.9rem;
  color: var(--color-textSecondary);
  border-top: 1px dashed var(--color-divider);
  padding-top: 12px;
  margin-top: auto;
}

/* 空状态和欢迎状态 */
.empty-state, .welcome-state {
  text-align: center;
  padding: 40px;
  animation: fadeIn 0.5s ease;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 20px;
  opacity: 0.6;
  color: var(--color-textSecondary);
}

.empty-state h3, .welcome-state h2 {
  color: var(--color-textPrimary);
  margin-bottom: 10px;
}

.empty-state p, .welcome-state p {
  color: var(--color-textSecondary);
  margin-bottom: 20px;
}

.empty-state a, .welcome-state a {
  color: var(--color-accent);
  cursor: pointer;
}

.empty-state a:hover, .welcome-state a:hover {
  text-decoration: underline;
}

/* 欢迎页插图 */
.welcome-illustration {
  position: relative;
  width: 200px;
  height: 200px;
  margin: 0 auto 30px;
}

.illustration-circle {
  position: absolute;
  width: 150px;
  height: 150px;
  background: var(--color-accent);
  opacity: 0.1;
  border-radius: 50%;
  top: 25px;
  left: 25px;
}

.illustration-doc {
  position: absolute;
  width: 100px;
  height: 140px;
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: 8px;
  top: 30px;
  left: 50px;
  box-shadow: 0 4px 12px var(--color-shadow);
}

.illustration-search {
  position: absolute;
  width: 80px;
  height: 80px;
  background: var(--color-accent);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
  color: white;
  bottom: 20px;
  right: 20px;
  box-shadow: 0 4px 12px var(--color-shadow);
}

/* 快速操作按钮 */
.quick-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-top: 20px;
}

.quick-actions button {
  padding: 10px 20px;
  background: var(--color-accent);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.quick-actions button:hover {
  background: var(--color-accentHover);
  transform: translateY(-2px);
}

/* 过渡动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}

@media (max-width: 768px) {
  .results-grid {
    grid-template-columns: 1fr;
  }
  
  .results-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .search-box {
    flex-direction: column;
  }
  
  .search-box input {
    padding: 12px;
  }
  
  .search-box button {
    padding: 12px;
  }
}
</style>